// Copyright (c) Microsoft Corporation.  All rights reserved.

#include "StdAfx.h"
#include "EventRecord.h"
#include "EventEnumerator.h"
#include "EventFile.h"

//Event Logging Functions: ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.WIN32COM.v10.en/debug/base/event_logging_functions.htm

namespace Microsoft { namespace Samples { namespace SqlServer { namespace SSIS { namespace EventLogSource {
	EventFile::EventFile(String^ fileName, String^ sourceName) { 
		Initialize(nullptr, fileName, sourceName);
	}

	EventFile::EventFile(String^ machineName, String^ fileName, String^ sourceName) {
		Initialize(machineName, fileName, sourceName);
	}

	EventFile::!EventFile() {
		if(this->LogHandle != NULL) {
			// if there is an enumerator, delete it because it references the log handle
			if(this->enumerator != nullptr) {
				delete this->enumerator;
				this->enumerator = nullptr;
			}

			// close the reference to the unmanaged log handle
			CloseEventLog(this->LogHandle);
			this->LogHandle = NULL;
		}
	}

	void EventFile::Initialize(String^ machineName, String^ fileName, String^ sourceName) {
		this->recordCount = 0;
		this->machineName = machineName;
		this->fileName = fileName;
		this->sourceName = sourceName;

		pin_ptr<const wchar_t> fileNamePtr = PtrToStringChars(fileName);
		pin_ptr<const wchar_t> machineNamePtr = PtrToStringChars(machineName);

		this->LogHandle = OpenBackupEventLog(machineNamePtr, fileNamePtr);

		if(this->LogHandle == nullptr) {
			throw gcnew Win32Exception();
		}
	}

	IEnumerator^ EventFile::GetEnumerator() {
		if(this->enumerator == nullptr) {
			this->enumerator = gcnew EventEnumerator(this);
		}
		return this->enumerator;
	}

	UInt32 EventFile::GetNewestRecordID() {
		return GetOldestRecordID() + GetRecordCount() - 1;
	}

	UInt32 EventFile::GetOldestRecordID() {
		DWORD oldestRecordID = 0;
		BOOL success = GetOldestEventLogRecord(this->LogHandle, &oldestRecordID);
		if(!success) {
			throw gcnew Win32Exception();
		}

		return oldestRecordID;
	}

	UInt32 EventFile::GetRecordCount() {
		DWORD recordCount = 0;
		BOOL success = GetNumberOfEventLogRecords(this->LogHandle, &recordCount);
		if(!success) {
			throw gcnew Win32Exception();
		}

		return recordCount;
	}

	String^ EventFile::MachineName::get() {
		return this->machineName;
	}

	String^ EventFile::SourceName::get() {
		return this->sourceName;
	}

	String^ EventFile::FileName::get() {
		return this->fileName;
	}
} } } } }